<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="设备编号" prop="deviceNo">
        <el-input
          v-model="queryParams.deviceNo"
          placeholder="请输入设备编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="通道号" prop="channel">
        <el-input
          v-model="queryParams.channel"
          placeholder="请输入设备通道"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="测试状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择测试状态"
          clearable
          style="width: 180px"
        >
          <el-option
            v-for="dict in dict.type.otu_measure_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="测试结果" prop="circuitStatus">
        <el-select
          v-model="queryParams.circuitStatus"
          placeholder="请选择测试结果"
          clearable
          style="width: 180px"
        >
          <el-option
            v-for="dict in dict.type.otu_circuit_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="参考曲线" prop="defaultMeasure">
        <el-select
          v-model="queryParams.defaultMeasure"
          placeholder="是否是参考曲线"
          clearable
          style="width: 180px"
        >
          <el-option
            v-for="dict in dict.type.otu_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['base:circuitMeasure:remove']"
        >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['base:circuitMeasure:export']"
        >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['base:circuitMeasure:import']"
        >导入</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
        :columns="columns"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="circuitMeasureList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="设备编号"
        align="center"
        prop="deviceNo"
        v-if="columns[0].visible"
      />
      <el-table-column
        label="通道号"
        align="center"
        prop="channel"
        v-if="columns[1].visible"
      />
      <el-table-column
        label="测试来源"
        align="center"
        prop="type"
        v-if="columns[2].visible"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.otu_measure_type"
            :value="scope.row.type"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="是否是参考曲线"
        align="center"
        prop="defaultMeasure"
        v-if="columns[3].visible"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.otu_yes_no"
            :value="scope.row.defaultMeasure"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="测试状态"
        align="center"
        prop="status"
        v-if="columns[4].visible"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.otu_measure_status"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="测试结果"
        align="center"
        prop="circuitStatus"
        v-if="columns[5].visible"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.otu_circuit_status"
            :value="scope.row.circuitStatus"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="失败原因"
        align="center"
        prop="remark"
        v-if="columns[6].visible"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.otu_failure_reason"
            :value="scope.row.remark"
          />
          <div></div>
        </template>
      </el-table-column>
      <el-table-column
        label="测试参数"
        align="center"
        prop="params"
        v-if="columns[7].visible"
      >
        <template #default="{row}">
          <el-popover
            placement="right-start"
            width="580"
            trigger="hover"
            popper-class="param-detail-popover"
          >
            <div class="param-detail-container">
              <h4 class="param-title">测试参数详情</h4>

              <!-- 基础参数组 -->
              <div class="param-group">
                <div class="param-group-title">基础设置</div>
                <div class="param-grid">
                  <div class="param-item">
                    <span class="param-label">波长：</span>
                    <span class="param-value">{{ row.paramWaveLength || '-' }}</span>
                  </div>
                  <div class="param-item">
                    <span class="param-label">量程(m)：</span>
                    <span class="param-value">{{ row.paramRd === 0 ? '自动' : row.paramRd || '-' }}</span>
                  </div>
                  <div class="param-item">
                    <span class="param-label">脉宽(ns)：</span>
                    <span class="param-value">{{ row.paramPw === 0 ? '自动' : row.paramPw || '-' }}</span>
                  </div>
                  <div class="param-item">
                    <span class="param-label">平均时间(s)：</span>
                    <span class="param-value">{{ row.paramTestTime || '-' }}</span>
                  </div>
                </div>
              </div>

              <!-- 测试模式 -->
              <div class="param-group">
                <div class="param-group-title">测试模式</div>
                <div class="param-item-full">
                  <span class="param-label">模式：</span>
                  <span class="param-value">
              {{
                      row.paramTestMode === 0 ? '平均测试' :
                        row.paramTestMode === 1 ? '实时测试' :
                          row.paramTestMode === 2 ? '后台测试' : '-'
                    }}
            </span>
                </div>
              </div>

              <!-- 光学参数组 -->
              <div class="param-group">
                <div class="param-group-title">光学参数</div>
                <div class="param-grid">
                  <div class="param-item">
                    <span class="param-label">折射率：</span>
                    <span class="param-value">{{ formatDecimal(row.paramIor) || '-' }}</span>
                  </div>
                  <div class="param-item">
                    <span class="param-label">回散系数：</span>
                    <span class="param-value">{{ formatDecimal(row.paramBackScatter) || '-' }}</span>
                  </div>
                </div>
              </div>

              <!-- 阈值参数组 -->
              <div class="param-group">
                <div class="param-group-title">阈值设置</div>
                <div class="param-grid">
                  <div class="param-item">
                    <span class="param-label">非反射门限：</span>
                    <span class="param-value">{{ formatDecimal(row.paramNonReflectThreshold) || '-' }}</span>
                  </div>
                  <div class="param-item">
                    <span class="param-label">反射门限：</span>
                    <span class="param-value">{{ formatDecimal(row.paramReflectThreshold) || '-' }}</span>
                  </div>
                  <div class="param-item">
                    <span class="param-label">结束门限：</span>
                    <span class="param-value">{{ formatDecimal(row.paramFinalThreshold) || '-' }}</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 触发元素 -->
            <template #reference>
              <div class="param-trigger">
                <i class="el-icon-setting"></i>
                <span>参数详情</span>
              </div>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <!--      <el-table-column label="备注" align="center" prop="remark" v-if="columns[8].visible"/>-->
      <el-table-column
        label="测试时间"
        align="center"
        prop="createTime"
        width="180"
        v-if="columns[8].visible"
      >
        <template slot-scope="scope">
          <span>{{
              parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
            }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status == 0"
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="lookCurve(scope.row)"
            v-hasPermi="['base:circuitMeasure:edit']"
          >查看曲线</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateDefaultMeasure(scope.row)"
            v-hasPermi="['base:circuitMeasure:edit']"
          >设为参考曲线</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['base:circuitMeasure:remove']"
          >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleSorExport(scope.row)"
            v-hasPermi="['base:circuitMeasure:export']"
          >导出sor文件</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 曲线导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".sor"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <div class="el-upload_-tip text-center" slot="tip">
          <span>仅允许导入sor格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确定</el-button>
        <el-button @click="upload.open = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCircuitMeasure,
  getCircuitMeasure,
  delCircuitMeasure,
  setDefaultMeasure,
} from "@/api/base/circuitMeasure";
import { getToken } from "@/utils/auth";
import {parseTime} from "@/utils/pulse";

export default {
  name: "CircuitMeasure",
  dicts: [
    "otu_measure_type",
    "otu_circuit_status",
    "otu_measure_status",
    "otu_yes_no",
    "otu_failure_reason",
  ],

  data() {
    return {
      showChart: false, //查看曲线的弹框

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 光路监测表格数据
      circuitMeasureList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 文件导入
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/base/circuitMeasure/importData",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        circuitId: null,
        deviceNo: null,
        type: null,
        defaultMeasure: null,
      },
      // 表单参数
      form: {},
      // 列信息
      columns: [
        { key: 0, label: "设备编号", visible: true },
        { key: 1, label: "通道号", visible: true },
        { key: 2, label: "测试来源", visible: true },
        { key: 3, label: "是否是参考曲线", visible: true },
        { key: 4, label: "测试状态", visible: true },
        { key: 5, label: "测试结果", visible: true },
        { key: 6, label: "失败原因", visible: true },
        { key: 7, label: "测试参数", visible: true },
        // { key: 8, label: `备注`, visible: false },
        { key: 8, label: "测试时间", visible: true },
      ],
      // 表单校验
      rules: {
        type: [
          {
            required: true,
            message: "1：点名测试  2：定期测试  3：复测不能为空",
            trigger: "change",
          },
        ],
        defaultMeasure: [
          {
            required: true,
            message: "0：非参考线  1：参考线不能为空",
            trigger: "blur",
          },
        ],
        paramSample: [
          {
            required: true,
            message: "测量精度 1: 高精度 0:低精度不能为空",
            trigger: "blur",
          },
        ],
        status: [{ required: true, message: "", trigger: "change" }],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询光路监测列表 */
    getList() {
      this.loading = true;
      listCircuitMeasure(this.queryParams).then((response) => {
        this.circuitMeasureList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        measureId: null,
        circuitId: null,
        deviceNo: null,
        type: null,
        defaultMeasure: null,
        paramLd: null,
        paramRd: null,
        paramPw: null,
        paramAt: null,
        paramSample: null,
        paramIor: null,
        paramBc: null,
        paramLt: null,
        paramRt: null,
        paramEt: null,
        paramLive: null,
        fileId: null,
        status: null,
        circuitStatus: null,
        remark: null,
        measureMode: null,
        regionId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.measureId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 && 不在后台添加*/
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加光路监测";
    },
    /** 修改按钮操作 && 不允许修改曲线*/
    handleUpdate(row) {
      this.reset();
      const measureId = row.measureId || this.ids;
      getCircuitMeasure(measureId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改光路监测";
      });
    },
    /** 设置参考曲线 */
    handleUpdateDefaultMeasure(row) {
      const measureId = row.measureId;
      this.$modal
        .confirm(
          '是否确认设置编号为 "' +
          measureId +
          '" 的曲线为参考曲线？设置后将取消光路的原参考曲线。'
        )
        .then(function () {
          return setDefaultMeasure(measureId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("设置成功");
        })
        .catch(() => {});
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.measureId != null) {
            updateCircuitMeasure(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCircuitMeasure(this.form).then((response) => {
              this.$modal.msgSuccess("增加成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const measureIds = row.measureId || this.ids;
      this.$modal
        .confirm("是否确认删除?")
        .then(function () {
          return delCircuitMeasure(measureIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "base/circuitMeasure/export",
        {
          ...this.queryParams,
        },
        `circuitMeasure_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "导入";
      this.upload.open = true;
    },
    /** 导出sor文件按钮操作 */
    handleSorExport(row) {
      console.log(row)
      this.download(
        "base/circuitMeasure/exportSor",
        {
          ...row,
        },
        `${row.deviceNo}_${row.channel}_${parseTime(row.createTime, "{y}{m}{d}{h}{i}{s}")}.sor`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    //不使用多选形式查看曲线
    lookCurve(e) {
      //查看曲线
      let that = this;
      const measureIds = e.measureId || this.ids;
      if (measureIds.length < 1) {
        this.$modal.msgWarning("请选择曲线");
        return;
      }
      that.$router.push("/lookCurve?measureId=" + e.measureId);
    },
    formatDecimal(value) {
      if (value === null || value === undefined || value === '') return '-'

      // 处理科学计数法 (如 1.23e-7)
      if (typeof value === 'string' && value.includes('e')) {
        try {
          value = Number(value).toString()
        } catch (e) {
          return value
        }
      }

      const num = typeof value === 'string' ? parseFloat(value) : value
      if (isNaN(num)) return value

      // 处理极小值，避免显示 0.00
      if (Math.abs(num) < 0.01 && num !== 0) {
        return num.toExponential(2)
      }

      return num.toFixed(2)
    }
  },
};
</script>


<style scoped>
.param-trigger {
  display: inline-flex;
  align-items: center;
  color: #409EFF;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 4px;
  transition: all 0.3s;
}
.param-trigger:hover {
  background-color: #f5f7fa;
}
.param-trigger i {
  margin-right: 5px;
}
</style>

<style>
/* 全局样式，因为 popover 是插入到 body 的 */
.param-detail-popover {
  max-width: 600px !important;
}
.param-detail-container {
  padding: 10px;
  font-size: 14px;
}
.param-title {
  margin: 0 0 15px 0;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
  color: #303133;
  font-size: 16px;
  font-weight: 500;
}
.param-group {
  margin-bottom: 15px;
}
.param-group-title {
  margin: 5px 0;
  padding-left: 5px;
  color: #606266;
  font-weight: 500;
  border-left: 3px solid #409EFF;
}
.param-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px 20px;
  padding: 8px 5px;
}
.param-item {
  display: flex;
  min-width: 0;
}
.param-item-full {
  padding: 8px 5px;
}
.param-label {
  color: #909399;
  white-space: nowrap;
}
.param-value {
  color: #303133;
  font-weight: 500;
  margin-left: 5px;
  word-break: break-all;
}
</style>
